package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.entity.Users;
import com.example.demo.service.UserService;
import com.example.demo.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;

@Slf4j
@RestController
@RequestMapping("/sys-user")
public class loginController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;
    @PostMapping("/login")
    public JsonResult<User> login( @RequestBody User user){
       log.info(user.toString());
        User login = userService.login(user);
        //HttpSession session = request.getSession();
        //session.setAttribute("username",login.getUserName());
        redisTemplate.opsForValue().set("username",login.getUserName());
        //log.info("login"+session.getAttribute("username"));
        return new JsonResult<>(200, login);
    }
    //注册功能
    @PostMapping("/register")
    public JsonResult<Void> reg(@RequestBody User user){
        System.out.println(user);
        userService.reg(user);
        JsonResult<Void> result = new JsonResult<>(200,null);
        return result;
    }

    /**分页查询功能
     * queryInfo:{
     *                 permission:1,权限
     *                 pagenum:0,页数
     *                 pagesize:2,尺寸
     *                 query:''
     *             }
     * @return
     */
    @GetMapping("/users")
    public JsonResult<Users> pageSearch(@RequestParam("permission")int permission,@RequestParam("pagenum") int pageNum,@RequestParam("pagesize") int pageSize,@RequestParam("query")String query){
        log.info("成功了"+query);
        System.out.println(permission+pageNum+pageSize);
        User[] users = userService.pageUser((pageNum-1)*pageSize, pageSize, permission,query);
        Users users1=new Users<User>();
        users1.setUsers(Arrays.asList(users));
        users1.setTotal(userService.all(permission,query));
        log.info(users1.toString());
        return new JsonResult<>(200, users1);
    }
    //修改用户信息
    @PutMapping("/update")
    public JsonResult<String> update(@RequestBody User user){
        //log.info("修改用户信息"+session.getAttribute("username"));
        userService.update(user.getId(),user.getName(),user.getStatus(), (String) redisTemplate.opsForValue().get("username"),user.getUserName());
        return new JsonResult<>(200, "修改成功");
    }
    //查询用户信息
    @GetMapping("/user/{userName}")
    public JsonResult<User> user(@PathVariable String userName){
        log.info("byUsername：用户账号"+userName);
        User user=userService.byUsername(userName);
        return new JsonResult<User>(200,user);
    }
}
